package com.test.dubbo.netty;

import com.test.dubbo.DubboProtocol;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;

public class NettyClientHandler extends SimpleChannelInboundHandler<DubboProtocol> implements InvocationHandler
{


    private String beanName;
    private ChannelHandlerContext context;//上下文
    private String result; //返回的结果
    public void setBeanName (String beanName)
    {
        this.beanName = beanName;
    }
    //与服务器的连接创建后，就会被调用, 这个方法是第一个被调用(1)
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(" channelActive 被调用  ");
        context = ctx; //因为我们在其它方法会使用到 ctx
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }


    @Override
    public synchronized Object invoke (Object proxy, Method method, Object[] args) throws Throwable
    {
        String s = this.beanName + "#" + method.getName () + "#" + args[0];
        DubboProtocol dubboProtocol = new DubboProtocol (s);
        context.writeAndFlush (dubboProtocol);
        wait ();
        String str = result;
        return str;
    }

    @Override
    protected synchronized void channelRead0 (ChannelHandlerContext channelHandlerContext, DubboProtocol dubboProtocol)
            throws Exception
    {
        System.out.println(" channelRead 被调用  ");
        byte[] content = dubboProtocol.getContent ();
        result = new String(content,"utf-8");
        notify ();
    }
}
